$(function() {
    localStorage.setItem('ThinkJS-Token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6IjEiLCJsb2dpbl9uYW1lIjoiYWRtaW4iLCJwYXNzd29yZCI6Ijk2ZTc5MjE4OTY1ZWI3MmM5MmE1NDlkZDVhMzMwMTEyIiwibmFtZSI6IlRoaW5rSlPkuIDlk6UiLCJlbWFpbCI6Imhld3UxMTIyQDE2My5jb20iLCJwaG9uZSI6IjE3MzQyMDY1OTA5IiwibG9naW5faXAiOiI6OjEiLCJsb2dpbl9kYXRlIjoiMjAxOC0wMS0wOCAxNjoyMjo1MSIsImNyZWF0ZV9kYXRlIjoiMjAxNy0xMi0xNCAxMTo1Mjo0NiIsInVwZGF0ZV9kYXRlIjoiMjAyMi0wNi0xNyAyMjo1MTowMyIsImRlbF9mbGFnIjoiMCIsInJvbGVfaWQiOlsiMWM1NGUwMDNjMWZjNGRjZDliMDg3ZWY4ZDQ4YWJhYzMiXSwic3RhdHVzIjoxLCJkZWZhdWx0X2RhdGEiOiIxIiwicm9sZW5hbWUiOlsi6LaF57qn566h55CG5ZGYIl19LCJpYXQiOjE2NTc2MDgyNDd9.-X5RJIoU80SvSznZcbmv5k6OFZhnlcS8BfQlDNSeQGc')
    let layer = layui.layer
    let form = layui.form
    let seclectArr = []
    let Q = {
        advimgdesc: '',
        advimgpos: '',
        page: 1,
        limit: 10
    }

    // 封装一个渲染列表的函数 做一个请求
    renderTable()

    function renderTable() {
        axios({
            method: 'GET',
            url: '/ydd_advimg/list',
            params: Q,
            headers: {
                "x-token": localStorage.getItem('ThinkJS-Token')
            }
        }).then(function(res) {
            // console.log(res);
            initTable(res.data.data.data)
            renderPage(res.data.data.count)
        })
    };

    function initTable(res) {
        let newArr = []
        newArr = res.map((item, index) => {
            return `
                <tr>
                    <td>
                        <input type="checkbox" class="status">
                    </td>
                    <td>${index}</td>
                    <td class = "advposname" >${item.advposname}</td>
                    <td class = "advposdesc">${item.advimgdesc}</td>
                    <td class = "default_data">
                    <img src="http://124.223.14.236:8060/${item.advimgsrc}" >
                    </td>
                    <td class = "advpossize">${item.advimglink}</td>
                    <td class="td">
                        <div class="layui-form-item">
                            <button type="button" class="layui-btn layui-btn-normal btn-radius" index="${item.id}" id="edit_btn">
                            <i class="layui-icon layui-icon-edit"></i>  
                        </button>
                            <button type="button" class="layui-btn layui-btn-danger btn-radius" index="${item.id}" id = "del_btn">
                            <i class="layui-icon layui-icon-delete"></i>  
                        </button>
                        </div>
                    </td>
                </tr>
                `
        })
        $('.advpos_table tbody').empty().append(newArr.join(''))
        seclectArr = res.map(item => {
                return `<option>${item.advimgpos}</option>`
            })
            // console.log(seclectArr.join(''));
        seclectArr.unshift('<option >请选择广告位</option>')
        setTimeout(function() {
            $('.advpos_head #advposition').empty().append(seclectArr.join(''))
        }, 2000)
    };
    // 利用代理的方式给编辑按钮添加点击事件
    let indexEdit = null
    $("tbody").on('click', '#edit_btn', function() {
        indexEdit = layui.layer.open({
            type: 1,
            area: ['700px', '400px'],
            title: '修改广告图',
            content: $('#table_edit').html()
        });
        form.render()
        let id = $(this).attr('index')
        axios({
            method: 'GET',
            url: '/ydd_advimg/rowInfo?id=' + id,
            headers: {
                "x-token": localStorage.getItem('ThinkJS-Token')
            }
        }).then(function(res) {
            form.val('form_edit', res.data.data)
        })
    });
    // 利用代理的方式给弹出层里面的取消按钮添加点击事件
    $('body').on('click', '#cancle_btn', function() {
        layer.close(indexEdit)
    });

    // 利用代理的方式给弹出层表单添加submit
    $('body').on('submit', '#form_edit', function(e) {
        e.preventDefault()
        console.log(111);
        axios({
            method: 'POST',
            url: '/ydd_advimg/update',
            data: $(this).serialize(),
            headers: { "x-token": localStorage.getItem('ThinkJS-Token') }
        }).then(function(res) {
            if (res.status === 200) {
                layer.msg('修改成功')
                layer.close(indexEdit)
                renderTable()
            } else {
                layer.msg('修改失败')
            }
        })
    });
    // 给弹出层里面的 点击上传添加 点击事件
    $('body').on('click', '#up_btn', function() {
            console.log(111);
            $('body #coverFile').click()
        })
        // 利用代理的方式给表格里面的删除按钮添加点击事件
    $('tbody').on('click', '#del_btn', function() {
        let len = $('tbody #del_btn').length
        let id = $(this).attr('index')
        axios({
            method: 'GET',
            url: '/ydd_advimg/del?id=' + id,
            headers: { "x-token": localStorage.getItem('ThinkJS-Token') }
        }).then(function(res) {
            console.log(res);
            if (res.data.errno === 0) {
                layer.msg('删除成功')
                if (len === 1) {
                    Q.page = Q.page === 1 ? 1 : Q.page - 1
                }
                renderTable()
            } else {
                layer.msg('删除失败')

            }

        })
    });
    // 给新增按钮添加点击事件
    let indexAdd = null
    $('.add_btn').on('click', function() {
        indexAdd = layui.layer.open({
            type: 1,
            area: ['700px', '400px'],
            title: '修改广告位',
            content: $('#table_edit').html()
        });
    });
    // 给弹出层的表单添加提交事件
    $('body').on('submit', '#form_edit', function(e) {
        e.preventDefault()
        let fd = new FormData($(this)[0])
        axios({
            method: 'POST',
            url: '/ydd_advimg/add',
            data: fd,
            headers: {
                "x-token": localStorage.getItem('ThinkJS-Token'),
                "Content-Type": "multipart/form-data"
            },
            contentType: false,
            processDate: false
        }).then(function(res) {
            if (res.data.errno === 0) {
                layer.msg('添加成功')
                layer.close(indexAdd)
                renderTable()
            } else {
                layer.msg('添加失败')
            }
        })
    });
    // 给弹出层的取消按钮添加点击事件
    $('body').on('click', '#cancle_btn', function() {
        layer.close(indexAdd)
    });
    // 右边工具栏部分
    // 鼠标移入button按钮显示 移出隐藏
    $('#tip_btn').hover(function() {
        $('.filter_tip').show()
    }, function() {
        $('.filter_tip').hide()
    });
    $('#refresh_btn').hover(function() {
        $('.filter_refresh').show()
    }, function() {
        $('.filter_refresh').hide()
    });
    // 鼠标点击 广告位头部隐藏 再次点击显示
    // $('#tip_btn').toggle(function() {
    //     $('.advpos_head')
    // }, function() {
    //     $('.advpos_head').show()
    // })
    let isBtnTrue = true
    $('#tip_btn').on('click', function() {
        if (isBtnTrue) {
            $('.advpos_head').hide()
            $('.tip_info').html('打开搜索区')
            $('.layui-input-bar #change').removeClass('layui-icon-up').addClass('layui-icon-down')
            isBtnTrue = false
        } else {
            $('.advpos_head').show()
            $('.tip_info').html('关闭搜索区')
            $('.layui-input-bar #change').removeClass('layui-icon-down').addClass('layui-icon-up')
            isBtnTrue = true
        }
    });
    $('#refresh_btn').on('click', function() {
        history.go(0)
    });
    //点击工具盒子 这个按钮 filter_tooltip 显示 再次点击隐藏
    let isTool_BtnTrue = true
    $('#tooltip_btn').on('click', function() {
        // console.log($('.checkbox [name = advposname]').prop('checked'));

        if (isTool_BtnTrue) {
            $('.filter_tooltip').show()
            isTool_BtnTrue = false
        } else {
            $('.filter_tooltip').hide()
            isTool_BtnTrue = true
        }
    });
    // 封装函数 判断复选框里面的checked的值来决定表格的列是显示还是隐藏
    // tableShow(advposname)
    // tableShow(advposdesc)
    // tableShow(default_data)
    // tableShow(advpossize)

    $('.checkbox [name = advposname]').on('change', function() {
        if ($(this).prop('checked')) {
            $('thead #advposname').show()
            $('tbody .advposname').show()
        } else {
            $('thead #advposname').hide()
            $('tbody .advposname').hide()
        }
    })
    $('.checkbox [name = advposdesc]').on('change', function() {
        if ($(this).prop('checked')) {
            $('thead #advposdesc').show()
            $('tbody .advposdesc').show()
        } else {
            $('thead #advposdesc').hide()
            $('tbody .advposdesc').hide()
        }
    })
    $('.checkbox [name = default_data]').on('change', function() {
        if ($(this).prop('checked')) {
            $('thead #default_data').show()
            $('tbody .default_data').show()
        } else {
            $('thead #default_data').hide()
            $('tbody .default_data').hide()
        }
    })
    $('.checkbox [name = advpossize]').on('change', function() {
        if ($(this).prop('checked')) {
            $('thead #advpossize').show()
            $('tbody .advpossize').show()
        } else {
            $('thead #advpossize').hide()
            $('tbody .advpossize').hide()
        }
    })

    // 分页区域
    // 定义一个分页的函数
    function renderPage(total) {
        // console.log(total);
        layui.laypage.render({
            elem: 'page_box',
            count: total,
            limit: Q.limit,
            curr: Q.page,
            layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
            limits: [2, 3, 5, 10],
            jump: function(obj, first) {
                // console.log(obj.curr);
                Q.page = obj.curr
                Q.limit = obj.limit
                    // initTable()
                if (!first) {
                    renderTable()
                }
            }
        })
    }
    // 头部筛选广告名称的功能
    $('.advpos_head .search_btn').on('click', function() {

        let str = $('.advpos_head .layui-input').val()
            // Q.advimgdesc = str
        let str1 = $('.advpos_head [name =advposname ]').val()
            // console.log(str);
            // Q.advimgpos = str1
        axios({
            method: 'GET',
            url: '/ydd_advimg/list',
            params: Q,
            headers: { "x-token": localStorage.getItem('ThinkJS-Token') }
        }).then(function(res) {
            console.log(res);
            let newArr = res.data.data.data.filter(item => {
                    return item.advimgdesc.includes(str) || item.advimgpos.includes(str1)
                })
                // console.log(newArr);
            initTable(newArr)
            renderPage(newArr.length)
        })

    });
    // 点击重置按钮 列表数据恢复正常
    $('.advpos_head .reset_btn').on('click', function() {
        renderTable()
    });

    // 全选与全不选
    $('.thead #check').on('change', function() {
        if ($(this).prop('checked')) {
            $('.adpos_bar .del_btn').show()
        } else {
            $('.adpos_bar .del_btn').hide()
        }
        $('tbody .status').prop('checked', $(this).prop('checked'))
    })
    $('tbody').on('change', '.status', function() {
        let len = $('tbody .status').length
        console.log($('tbody .status:checked').length);
        if ($('tbody .status:checked').length == len) {
            $('.thead #check').prop('checked', true)
        } else(
            $('.thead #check').prop('checked', false)
        )
        if ($('tbody .status:checked').length !== 0) {
            $('.adpos_bar .del_btn').show()
        } else {
            $('.adpos_bar .del_btn').hide()
        }
    })


})